#include <iostream>
#include <string>
#include <unordered_map>
#include <cstring>
#include <cstdlib>
#include <ctype.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"

static void Usage(const std::string porc)
{
    std::cout << "Usage:\n\t" << porc << " port [ip]" << std::endl;
}

class UdpServer
{
public:
    UdpServer(int port, std::string ip = "") : port_(port), ip_(ip), sockfd_(-1)
    {}

    ~UdpServer()
    {}
public:
    void init()
    {
        // 1.创建socket套接字
        sockfd_ = socket(AF_INET, SOCK_DGRAM, 0);
        if(sockfd_ < 0)
        {
            logMessage(FATAL, "socket:%s:%d", strerror(errno), sockfd_);
            exit(1);
        }
        logMessage(DEBUG, "socket create success: %d", sockfd_);
        // 2.绑定网络信息
        // 2.1 填充基本信息到struct sockaddr_in中
        struct sockaddr_in local;
        //bzero(&local, sizeof(local));
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        local.sin_addr.s_addr = ip_.empty() ? htonl(INADDR_ANY) : inet_addr(ip_.c_str());
        // 2.2 bind网络信息
        if(bind(sockfd_, (const struct sockaddr *)&local, sizeof(local)) == -1)
        {
            logMessage(FATAL, "bind: %s:%d", strerror(errno), sockfd_);
            exit(2);
        }
        logMessage(DEBUG, "socket bind success: %d", sockfd_);
    }

    void start()
    {
        char inbuffer[1024];
        char outbuffer[1024];

        while(true)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);

            ssize_t s = recvfrom(sockfd_, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if(s > 0)
            {
                inbuffer[s] = 0;
            }
            else if(s == -1)
            {
                logMessage(WARINING, "recvfrom: %s:%d", strerror(errno), sockfd_);
                continue;
            }

            std::string peerIp = inet_ntoa(peer.sin_addr);
            uint16_t peerPort = ntohs(peer.sin_port);

            checkOnlineUser(peerIp, peerPort, peer);

            logMessage(NOTICE, "[%s:%d]# %s", peerIp.c_str(), peerPort, inbuffer);

            messageRoute(peerIp, peerPort, inbuffer);
        }
    }

    void checkOnlineUser(std::string &ip, uint32_t port, struct sockaddr_in &peer)
    {
        std::string key = ip;
        key += ":";
        key += std::to_string(port);
        auto iter = users.find(key);
        if(iter == users.end())
        {
            users.insert({key, peer});
        }
        else
        {}
    }

    void messageRoute(std::string ip, uint16_t port, std::string info)
    {
        std::string message = "[";
        message += ip;
        message += ":";
        message += std::to_string(port);
        message += "]#";
        message += info;

        for(auto &user : users)
        {
            sendto(sockfd_, message.c_str(), message.size(), 0, (struct sockaddr *)&(user.second), sizeof(user.second));
        }
    }
private:
    uint16_t port_;
    std::string ip_;
    int sockfd_;
    std::unordered_map<std::string, struct sockaddr_in> users;
};

int main(int argc, char *argv[])
{
    if(argc != 2 && argc != 3)
    {
        Usage(argv[0]);
        exit(3);
    }

    uint16_t port = atoi(argv[1]);
    std::string ip;
    if(argc == 3)
    {
        ip = argv[2];
    }

    UdpServer svr(port, ip);
    svr.init();
    svr.start();

    return 0;
}